<?php
/* |====================================|
   |===========================================================================|
   |==============================================================================================|
   |==|	 >>> FUNCTIONS.PHP!
   |=================================================================================================================|
   |====================================================================================|
   |===================================================================|
   |===========================|
*/



/*
   >--------------------------------------------------------
	>>> INDEX OF FUNCTIONS
   >--------------------------------------------------------


   >------------------------------------------------------------------------------------------------------------------------------------
	>>> THEME SETUP AND SUPPORT FUNCTIONS
   >------------------------------------------------------------------------------------------------------------------------------------
	trudocsCustomScripts()							// ACTION - ADD SCRIPTS WE NEED TO THE THEME HEADER
	master_setup()									// ACTION - THEME NAVIGATION AND THUMBNAILS
	master_widgets_init()							// ACTION - THEME SIDEBARS
	disablePostCommentsFeedLink( $for_comments ) 	// FILTER - DISABLE COMMENT FEEDS / REMOVE FEED LINKS FROM HEAD
	
   >------------------------------------------------------------------------------------------------------------------------------------
	>>> BUDDYPRESS MODIFICATION FUNCTIONS
   >------------------------------------------------------------------------------------------------------------------------------------
	ap_bp_core_get_userlink( $userLink, $userID )		// FILTER - CUSTOM PROFILE COMMENT FOR AP'S - ONLY FIRST NAME AND LAST INITIAL, NO LINKS
	ap_activity_comment( $content  )					// FILTER - STRIPS NON <p> TAGS FROM BUDDYPRESS ACTIVITY FEED COMMENTS
	bp_mytheme_post_update()							// ACTION - ADD COMMENT FORM TO ALL PROFILES AND REMOVE @MENTION
	disable_activation_validation( $user_id )			// ACTION - NO MORE EMAIL ACTIVATION
	RP_screen_signup()									// ACTION - ATTACH CUSTOM REGISTRATION FUNCTION
	
   >------------------------------------------------------------------------------------------------------------------------------------
	>>> TRUDOCS CUSTOMIZATION FUNCTIONS
   >------------------------------------------------------------------------------------------------------------------------------------
	hide_wp_admin_bar($content)		// FILTER - HIDE THE WP TOOLBAR FOR NON-ADMIN USERS
	themes_url()					// RETURNS STRING - THE WP THEMES DIRECTORY URL
	curPageURL()					// RETURNS STRING - THE CURRENT URL
	is_ap( $id = '' )				// RETURNS BOOLEAN - CHECK MEMBER TYPE FUNCTIONS - USES CURRENT USER'S ID IF NONE IS PASSED
	is_ssa( $id = '' )				// RETURNS BOOLEAN - CHECK MEMBER TYPE FUNCTIONS - USES CURRENT USER'S ID IF NONE IS PASSED
	is_god( $id = '' )				// RETURNS BOOLEAN - CHECK MEMBER TYPE FUNCTIONS - USES CURRENT USER'S ID IF NONE IS PASSED
	is_aKey() 						// RETURNS BOOLEAN - TRUE IF THE CURRENT USER IS THE ACCESS KEY USER. $ID == 4
	logoutAccessKeyUser()			// ACTION - LOGOUT ACCESSKEY USER IF THEY LEAVE THE LISTING EDIT PAGE
	blockAdminAccess()				// ACTION - REDIRECT NON_ADMINS AWAY FROM WP_ADMIN
	docTypesArray()					// RETURNS ARRAY - AN ARRAY OF ALL DOCUMENT TYPE LABELS
	docsArray( $type = false )		// RETURNS ARRAY -  ARRAY OF ARRAYS WITH SUBMISSION DOCUMENTS INFO AND FILE PATHS

   >------------------------------------------------------------------------------------------------------------------------------------
	>>> RATING FUNCTIONS
   >------------------------------------------------------------------------------------------------------------------------------------
	ssa_rating_show( $userID )											// RETURNS STRING - DISPLAYS AN SSA's RATING / NOT CLICKABLE
	listing_rating_show( $postID )										// RETURNS STRING - DISPLAYS A LISTING'S RATING / NOT CLICKABLE
	rate_listing( $postID, $echo = true, $multiQueryParams = false )	// RETURNS STRING - DISPLAYS THE HTML FOR AP's TO RATE A LISTING / CLICKABLE
	set_listing_rating( $postID, $rating, $echo )						// NO RETURN - SETS A LISTING RATING
	set_ssa_rating_average( $userID )									// NO RETURN - UPDATES THE SSA's RATING
	set_ssa_rating_wieght( $userID )									// NO RETURN - CALCs AND SETS A SSA's WIEGHTED RATING
   >------------------------------------------------------------------------------------------------------------------------------------

	>>> DOCUMENT TRACKING / AUTO EMAILER FUNCTIONS
   >------------------------------------------------------------------------------------------------------------------------------------
	cron_add_every_three_days( $schedules )		// ACTION - CUSTOM CRON TIME
	queue_reqDocsMissingEmail()					// ACTION - ADD EMAIL FUNCTION TO CRON SCHED
	send_reqDocsMissingEmail()					// ACTION - REQUIRED DOC MISSING EMAILING FUNCTION
   >------------------------------------------------------------------------------------------------------------------------------------
*/



/*|=================|
  |====================================|
  |------------------------------------================================|
  |--------------------------------------------------------------------=================|
  |--| >>> THEME SETUP AND SUPPORT
  |--------------------------------------------------------------------========================================|
  |====================================================================================================================================|
  */



	// ADD SCRIPTS WE NEED TO THE HEADER
   //--------------------------------------------------
		function trudocsCustomScripts() {
			
			$themePath = themes_url() . '/master/';
			
			// ATTACH jQuery FROM GOOGLE BECAUSE OF THE WORDPRESS NO_CONFLICT THING: http://codex.wordpress.org/Function_Reference/wp_enqueue_script#jQuery_noConflict_wrappers
				wp_deregister_script('jquery'); // remove stock script
				wp_enqueue_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js' );
				
			if ( is_front_page() ) {
				// CAROUSEL FOR HOMEPAGE
					wp_enqueue_script( 'jqMousewheel', $themePath . 'scripts/jquery.mousewheel.min.js', array('jquery') );
					wp_enqueue_script( 'jqCarousel', $themePath . 'scripts/jquery.carousel-1.1.js', array('jquery') );
			} elseif ( is_page('submit-documents') || is_page('manage-listings') ) {
				// ZCLIP: COPYS A LINK TO CLIPBOARD
					wp_enqueue_script( 'jqZclip', $themePath . 'scripts/jquery.zclip.js', array('jquery') );
				// jTip TOOL TIPS
					wp_enqueue_script( 'jqJtip', $themePath . 'toolTips/jtip.js', array('jquery') );
			}
			
		}
		add_action('wp_enqueue_scripts', 'trudocsCustomScripts');

	// NAVIGATION AND THUMBNAILS
   //--------------------------------------------------
		function master_setup() {
			// This theme uses post thumbnails
				add_theme_support( 'post-thumbnails' );
			// This theme uses wp_nav_menu() in one location.
				register_nav_menus( array(
					'loggedOut' => __( 'Logged Out Menu', 'master' ),
					'AKU' => __( 'Access Key User Menu', 'master' ),
					'AP' => __( 'Agent Partner Menu', 'master' ),
					'SSA' => __( 'Short Sale Assistant Menu', 'master' ),
					'GOD' => __( 'Administrator Menu', 'master' ),
				) );
		}
		add_action( 'after_setup_theme', 'master_setup' );
		
	// LETS MAKE SOME SIDEBARS
   //--------------------------------------------------
		function master_widgets_init() {
			// Area 1, located at the top of the sidebar.
			register_sidebar( array(
				'name' => __( 'Primary Widget Area', 'master' ),
				'id' => 'primary-widget-area',
				'description' => __( 'The primary widget area', 'master' ),
				'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
				'after_widget' => '</li>',
				'before_title' => '<h3 class="sidebar-widget-title">',
				'after_title' => '</h3>',
			) );
			// Area 2, located below the Primary Widget Area in the sidebar. Empty by default.
			register_sidebar( array(
				'name' => __( 'Secondary Widget Area', 'master' ),
				'id' => 'secondary-widget-area',
				'description' => __( 'The secondary widget area', 'master' ),
				'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
				'after_widget' => '</li>',
				'before_title' => '<h3 class="sidebar-widget-title">',
				'after_title' => '</h3>',
			) );
			// Area 3, located in the footer. Empty by default.
			register_sidebar( array(
				'name' => __( 'First Footer Widget Area', 'master' ),
				'id' => 'first-footer-widget-area',
				'description' => __( 'The first footer widget area', 'master' ),
				'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
				'after_widget' => '</li>',
				'before_title' => '<h3 class="footer-widget-title">',
				'after_title' => '</h3>',
			) );
			// Area 4, located in the footer. Empty by default.
			register_sidebar( array(
				'name' => __( 'Second Footer Widget Area', 'master' ),
				'id' => 'second-footer-widget-area',
				'description' => __( 'The second footer widget area', 'master' ),
				'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
				'after_widget' => '</li>',
				'before_title' => '<h3 class="footer-widget-title">',
				'after_title' => '</h3>',
			) );
			// Area 5, located in the footer. Empty by default.
			register_sidebar( array(
				'name' => __( 'Third Footer Widget Area', 'master' ),
				'id' => 'third-footer-widget-area',
				'description' => __( 'The third footer widget area', 'master' ),
				'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
				'after_widget' => '</li>',
				'before_title' => '<h3 class="footer-widget-title">',
				'after_title' => '</h3>',
			) );
			// Area 6, located in the footer. Empty by default.
			register_sidebar( array(
				'name' => __( 'Fourth Footer Widget Area', 'master' ),
				'id' => 'fourth-footer-widget-area',
				'description' => __( 'The fourth footer widget area', 'master' ),
				'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
				'after_widget' => '</li>',
				'before_title' => '<h3 class="footer-widget-title">',
				'after_title' => '</h3>',
			) );
		}
		add_action( 'widgets_init', 'master_widgets_init' );
		
	// DISABLE COMMENT FEEDS / REMOVE FEED LINKS FROM HEAD
   //--------------------------------------------------
		function disablePostCommentsFeedLink( $for_comments ) {
			return;
		}
		add_filter('post_comments_feed_link','disablePostCommentsFeedLink');
		remove_action('wp_head','feed_links_extra', 3);
		remove_action('wp_head','feed_links', 2);





/*|=================|
  |====================================|
  |------------------------------------================================|
  |--------------------------------------------------------------------=================|
  |--------------------------------------------------------------------=================|
  |--| >>> BUDDYPRESS MODIFICATIONS
  |--------------------------------------------------------------------========================================|
  |====================================================================================================================================|
  */

	// CUSTOM PROFILE COMMENT - ONLY FIRST NAME AND LAST INITIAL, NO LINKS
   //----------------------------------------------------------------------------------------------------
		function ap_bp_core_get_userlink( $userLink, $userID ) {
			if ( !is_page('manage-listings') && is_ap() ) {
				$user = get_user_by( 'id', $userID );
				$display_name = $user->first_name . ' ' . substr($user->last_name, 0, 1);
				$url = bp_core_get_user_domain( $userID );
				$userLink = $display_name;
			}
			return $userLink;
		}
		add_filter ( 'bp_core_get_userlink', 'ap_bp_core_get_userlink', 11, 2 );
		
		function ap_activity_comment( $content  ) {
			$content = strip_tags( $content, '<p>' );
			return $content;
		}
		add_filter ( 'bp_insert_activity_meta', 'ap_activity_comment', 11, 1);

	
	// ADD COMMENT FORM TO ALL PROFILES AND REMOVE @MENTION
   //--------------------------------------------------
		remove_action( 'wp_ajax_post_update', 'bp_dtheme_post_update' );
		//add our own handler for activity posting
		add_action(  'wp_ajax_post_update', 'bp_mytheme_post_update' );
		/* AJAX update posting */
		function bp_mytheme_post_update() {
		global $bp;
		/* Check the nonce */
		check_admin_referer( 'post_update', '_wpnonce_post_update' );
		if ( !is_user_logged_in() ) {
		echo '-1';
		return false;
		}
		if ( empty( $_POST['content'] ) ) {
		echo '-1<div id="message"><p>' . __( 'Please enter some content to post.', 'buddypress' ) . '</p></div>';
		return false;
		}
		if ( empty( $_POST['object'] ) && function_exists( 'bp_activity_post_update' ) ) {
		//this is what I have changed
		if( !bp_is_home() && bp_is_member() ) {
			$content = "@". bp_get_displayed_user_username()." ".$_POST['content'];
		} else {
			$content = $_POST['content'];
		}
		$activity_id = bp_activity_post_update( array( 'content' => $content ) );
		//end of my changes
		} elseif ( $_POST['object'] == 'groups' ) {
		if ( !empty( $_POST['item_id'] )&&function_exists( 'groups_post_update' ) )
		$activity_id = groups_post_update( array( 'content' => $_POST['content'], 'group_id' => $_POST['item_id'] ) );
		} else
		$activity_id = apply_filters( 'bp_activity_custom_update', $_POST['object'], $_POST['item_id'], $_POST['content'] );
		if ( !$activity_id ) {
		echo '-1<div id="message"><p>' . __( 'There was a problem posting your update, please try again.', 'buddypress' ) . '</p></div>';
		return false;
		}
		if ( bp_has_activities ( 'include=' . $activity_id ) ) : ?>
		<?php while ( bp_activities() ) : bp_the_activity(); ?>
		<?php locate_template( array( 'activity/entry.php' ), true ) ?>
		<?php endwhile; ?>
		<?php endif;
		}
	
	// NO MORE EMAIL ACTIVATION
   //--------------------------------------------------
		function disable_activation_validation( $user_id ) {
		  global $wpdb;
		  $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->users SET user_status = 0 WHERE ID = %d", $user_id ) );
			add_filter( 'bp_registration_needs_activation', '__return_false' );
		}
		add_action( 'bp_core_signup_user', 'disable_activation_validation' );
		
	// CUSTOM REGISTRATION -- MORE THAN LIKELY WE"LL HAVE SOME BUGS WITH SSA REGISTRATION(when they can register) SINCE WPUF IS PULLING FROM THE WORDPRESS PROFILE NAME FIELDS AND BUDDYPRESS USES ITS OWN...	
   //------------------------------------------------------------------------------------------------------------------------------------------------------
		// FISRT REMOVE THE STOCK FUNCTION
		remove_action( 'bp_screens', 'bp_core_screen_signup' );
		// AND ATTACH OUR OWN
		function RP_screen_signup() {
			global $bp;	
			if ( !bp_is_current_component( 'register' ) )
				return;
			// Not a directory
			bp_update_is_directory( false, 'register' );
			// If the user is logged in, redirect away from here
			if ( is_user_logged_in() ) {
				if ( bp_is_component_front_page( 'register' ) )
					$redirect_to = trailingslashit( bp_get_root_domain() . '/manage-listings' );
				else
					$redirect_to = bp_get_root_domain();
				bp_core_redirect( apply_filters( 'bp_loggedin_register_page_redirect_to', $redirect_to ) );
				return;
			}
			if ( !isset( $bp->signup ) ) {
				$bp->signup = new stdClass;
			}
			$bp->signup->step = 'request-details';
			if ( !bp_get_signup_allowed() ) {
				$bp->signup->step = 'registration-disabled';
			// If the signup page is submitted, validate and save
			} elseif ( isset( $_POST['signup_submit'] ) && bp_verify_nonce_request( 'bp_new_signup' ) ) {
				
				// Check the base account details for problems
				$account_details = bp_core_validate_user_signup( $_POST['signup_username'], $_POST['signup_email'] );
				// If there are errors with account details, set them for display
				if ( !empty( $account_details['errors']->errors['user_name'] ) )
					$bp->signup->errors['signup_username'] = $account_details['errors']->errors['user_name'][0];
				if ( !empty( $account_details['errors']->errors['user_email'] ) )
					$bp->signup->errors['signup_email'] = $account_details['errors']->errors['user_email'][0]; 
					
					
				// CHECK THAT MY CUSTOM CODED FIELDS ARE FILLED OUT
				if ( !isset($_POST['signup_f_name']) || empty($_POST['signup_f_name']) )
					$bp->signup->errors['signup_f_name'] = 'Please provide your first name'; 
				if ( !isset($_POST['signup_l_name']) || empty($_POST['signup_l_name']) )
					$bp->signup->errors['signup_l_name'] = 'Please provide your last name'; 
				if ( !isset($_POST['signup_phone']) || empty($_POST['signup_phone']) )
					$bp->signup->errors['signup_phone'] = 'Please provide your phone number'; 
	
	
				// Check that both password fields are filled in
				if ( empty( $_POST['signup_password'] ) || empty( $_POST['signup_password_confirm'] ) )
					$bp->signup->errors['signup_password'] = __( 'Please make sure you enter your password twice', 'buddypress' );
				// Check that the passwords match
				if ( ( !empty( $_POST['signup_password'] ) && !empty( $_POST['signup_password_confirm'] ) ) && $_POST['signup_password'] != $_POST['signup_password_confirm'] )
					$bp->signup->errors['signup_password'] = __( 'The passwords you entered do not match.', 'buddypress' );
				$bp->signup->username = $_POST['signup_username'];
				$bp->signup->email = $_POST['signup_email'];
				do_action( 'bp_signup_validate' );
				// Add any errors to the action for the field in the template for display.
				if ( !empty( $bp->signup->errors ) ) {
					foreach ( (array) $bp->signup->errors as $fieldname => $error_message ) {
						// addslashes() and stripslashes() to avoid create_function()
						// syntax errors when the $error_message contains quotes
						add_action( 'bp_' . $fieldname . '_errors', create_function( '', 'echo apply_filters(\'bp_members_signup_error_message\', "<div class=\"error\">" . stripslashes( \'' . addslashes( $error_message ) . '\' ) . "</div>" );' ) );
					}
				} else {
					$bp->signup->step = 'save-details';
					// No errors! Let's register those deets.
					$active_signup = !empty( $bp->site_options['registration'] ) ? $bp->site_options['registration'] : '';
					if ( 'none' != $active_signup ) {
						// Hash and store the password
						$usermeta['password'] = wp_hash_password( $_POST['signup_password'] );
						$usermeta = apply_filters( 'bp_signup_usermeta', $usermeta );
						// Finally, sign up the user
						$wp_user_id = bp_core_signup_user( $_POST['signup_username'], $_POST['signup_password'], $_POST['signup_email'], $usermeta );
						if ( is_wp_error( $wp_user_id ) ) {
							$bp->signup->step = 'request-details';
							bp_core_add_message( $wp_user_id->get_error_message(), 'error' ); 
						} else {
	
	
							// SET CUSTOM CODED SIGNUP FIELDS NOW THAT WE HAVE A USER ID - $wp_user_id
							$fName = $_POST['signup_f_name'];
							$lName = $_POST['signup_l_name'];
							$apPhone = $_POST['signup_phone'];
							wp_update_user( array ('ID' => $wp_user_id, 'first_name' => $fName, 'last_name' => $lName, 'display_name' => $fName . ' ' . $lName ) ) ;
							update_user_meta( $wp_user_id, 'apPhone', $apPhone );
							
							
							$bp->signup->step = 'completed-confirmation';
						}
					}
					do_action( 'bp_complete_signup' );
				}
			}
			do_action( 'RP_screen_signup' );
			bp_core_load_template( apply_filters( 'bp_core_template_register', 'registration/register' ) );
		}
		add_action( 'bp_screens', 'RP_screen_signup' );



/*|=================|
  |====================================|
  |------------------------------------================================|
  |--------------------------------------------------------------------=================|
  |--| >>> TRUDOCS CUSTOMIZATION FUNCTIONS
  |--------------------------------------------------------------------========================================|
  |====================================================================================================================================|
  */



	// HIDE THE WP TOOLBAR FOR NON-ADMIN USERS
   //----------------------------------------------------------------------------------------------------
		function hide_wp_admin_bar($content) {
			return ( current_user_can( 'administrator' ) ) ? $content : false;
		}
		add_filter( 'show_admin_bar' , 'hide_wp_admin_bar');
		
	// SOME HELPER FUNCTIONS
   //--------------------------------------------------
		
		// RETURNS THE THEMES DIRECTORY URL
		function themes_url() {
		   $themes_url= get_theme_root_uri();
		   return $themes_url;
		}
		// RETURNS THE CURRENT URL
		function curPageURL() {
			$pageURL = 'http';
			if ( isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on" ) {$pageURL .= "s";}
			$pageURL .= "://";
			if ( $_SERVER["SERVER_PORT"] != "80" ) {
				$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
			} else {
				$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
			}
			return $pageURL;
		}
		
	// CHECK MEMBER TYPE FUNCTIONS - RETURNS BOOLEAN - USES CURRENT USER'S ID IF NONE IS PASSED
   //--------------------------------------------------
		function is_ap( $id = '' ) {
			if ( $id == '' ) { $id = get_current_user_id(); }
			$user = get_user_by( 'id', $id );
			if ( $user->roles[0] == 'subscriber' && $id != 4 ) {
				return true;
			} else {
				return false;
			}
		}
		function is_ssa( $id = '' ) {
			if ( $id == '' ) { $id = get_current_user_id(); }
			$user = get_user_by( 'id', $id );
			if ( $user->roles[0] == 'assistant' ) {
				return true;
			} else {
				return false;
			}
		}
		function is_god( $id = '' ) {
			if ( $id == '' ) { $id = get_current_user_id(); }
			$user = get_user_by( 'id', $id );
			if ( $user->roles[0] == 'administrator' ) {
				return true;
			} else {
				return false;
			}
		}
		function is_aKey() {
			global $current_user;
			if ( $current_user->ID == 4 ) {
				return true;
			} else {
				return false;
			}
		}
		
	// LOGOUT ACCESSKEY USER IF THEY LEAVE THE LISTING EDIT PAGE
   //--------------------------------------------------
		function logoutAccessKeyUser() {
			if ( get_current_user_id() == 4 && ( is_front_page() || is_page(array('submit-short-sale','how-it-works','short-sale-assistants','contact-us','manage-listings','register')) ) ) { // !isset($_GET['access'])
				wp_logout();
				wp_redirect(curPageURL());
			}
		}
		add_action( 'wp_head', 'logoutAccessKeyUser', 99 );
			
	// REDIRECT NON_ADMINS AWAY FROM WP_ADMIN
   //--------------------------------------------------
		function blockAdminAccess() {
			if ( ( is_admin() || in_array($GLOBALS['pagenow'], array('wp-login.php', 'wp-register.php')) ) && !is_god() ) {
				wp_redirect( home_url() );
				//exit;
			}
		}
		add_action( 'admin_head', 'blockAdminAccess' );
	
	// SUBMITTED DOCUMENTS FUNCTIONS
   //--------------------------------------------------
		function docTypesArray() { 
			return array( 'Listing', 'Purchase Contract', 'Homeowner', 'Lender', 'Title Company' );
		}
		function docsArray( $type = false ) {
			$listing = array(
				array( 'id' => 'ListingCoverChecklist', 'label' => 'Listing Cover Checklist', 'required' => true , 'fileURL' => 'http://trudocs.com/wp-content/downloads/ListingCoverChecklist.pdf', 'downloadURL' => 'download.php?file=ListingCoverChecklist.pdf' ),
				array( 'id' => 'AgentReferralForm', 'label' => 'Agent Referral Form (ARF)', 'required' => true , 'fileURL' => 'http://trudocs.com/wp-content/downloads/AgentReferralForm.pdf', 'downloadURL' => 'download.php?file=AgentReferralForm.pdf' ),
				array( 'id' => 'Comps', 'label' => 'Comps', 'required' => true , 'downloadURL' => false ),
				array( 'id' => 'ListingAgreement', 'label' => 'Listing Agreement', 'required' => true , 'downloadURL' => false ),
				array( 'id' => 'ListingShortSaleAddendum(SSA)', 'label' => 'Listing Short Sale Addendum (SSA)', 'required' => false , 'downloadURL' => false ),
				array( 'id' => 'MLS', 'label' => 'MLS', 'required' => true , 'downloadURL' => false ),
				array( 'id' => 'Pictures', 'label' => 'Pictures', 'required' => false , 'downloadURL' => false ),
				array( 'id' => 'RepairEstimates', 'label' => 'Repair Estimate', 'required' => false , 'fileURL' => 'http://trudocs.com/wp-content/downloads/EstimateofRepairsForm.pdf', 'downloadURL' => 'download.php?file=EstimateofRepairsForm.pdf' ),
			);
			$purchasecontract = array(
				array( 'id' => 'OfferChecklist', 'label' => 'Offer Checklist', 'required' => true , 'fileURL' => 'http://trudocs.com/wp-content/downloads/OfferChecklist.pdf', 'downloadURL' => 'download.php?file=OfferChecklist.pdf' ),
				array( 'id' => 'PurchaseContract', 'label' => 'Purchase Contract (PC)', 'required' => true , 'downloadURL' => false ),
				array( 'id' => 'PurchaseContractShortsaleAddendum', 'label' => 'Purchase Contract Shortsale Addendum (PCSSA)', 'required' => true , 'downloadURL' => false ),
				array( 'id' => 'PurchaseContractAddendum', 'label' => 'Purchase Contract Addendum', 'required' => false , 'downloadURL' => false ),
				array( 'id' => 'AsIsAddendum', 'label' => 'As Is Addendum', 'required' => false , 'downloadURL' => false ),
				array( 'id' => 'BuyerFacilitatorFee', 'label' => 'Buyer Facilitator Fee (BFF)', 'required' => true ),// 'fileURL' => 'http://trudocs.com/wp-content/downloads/BuyerFacilitationFeeAgreement.docx', 'downloadURL' => 'download.php?file=BuyerFacilitationFeeAgreement.docx' ),
				array( 'id' => 'Prequalification', 'label' => 'Prequalification', 'required' => false , 'downloadURL' => false ),
				array( 'id' => 'ProofofFunds', 'label' => 'Proof of Funds', 'required' => false , 'downloadURL' => false ),
				array( 'id' => 'CounterOfferAddendum', 'label' => 'Counter Offer / Addendum', 'required' => false , 'downloadURL' => false ),
			);
			$homeowner = array(
				array( 'id' => 'HomeownerChecklist', 'label' => 'Homeowner Checklist', 'required' => true , 'fileURL' => 'http://trudocs.com/wp-content/downloads/HomeownerChecklist.pdf', 'downloadURL' => 'download.php?file=HomeownerChecklist.pdf' ),
				array( 'id' => '3rdPartyAuthorization', 'label' => '3rd Party Authorization (ARI)', 'required' => true , 'fileURL' => 'http://trudocs.com/wp-content/downloads/ARI-RealPrompt.pdf', 'downloadURL' => 'download.php?file=ARI-RealPrompt.pdf' ),
				array( 'id' => 'MortgageStatement', 'label' => 'Mortgage Statement', 'required' => false , 'downloadURL' => false ),
				array( 'id' => 'HardshipLetter', 'label' => 'Hardship Letter', 'required' => false , 'fileURL' => 'http://trudocs.com/wp-content/downloads/SampleHarshipLetter.pdf', 'downloadURL' => 'download.php?file=SampleHarshipLetter.pdf' ),
				array( 'id' => 'FinancialForm', 'label' => 'Financial Form', 'required' => true , 'fileURL' => 'http://trudocs.com/wp-content/downloads/FinancialWorksheet.pdf', 'downloadURL' => 'download.php?file=FinancialWorksheet.pdf' ),
				array( 'id' => 'BankStatements', 'label' => 'Bank Statement', 'required' => false , 'downloadURL' => false ),
				array( 'id' => 'PayStubs', 'label' => 'Pay Stubs', 'required' => false , 'downloadURL' => false ),
				array( 'id' => 'ProofofIncome', 'label' => 'Proof of Income', 'required' => false , 'downloadURL' => false ),
				array( 'id' => 'Taxes', 'label' => 'Taxes (2yrs)', 'required' => false , 'downloadURL' => false ),
				array( 'id' => 'LetterofExplanation', 'label' => 'Letter of Explanation (LOE)', 'required' => false , 'downloadURL' => false ),
				array( 'id' => '4506T', 'label' => '4506T', 'required' => true , 'fileURL' => 'http://trudocs.com/wp-content/downloads/4506T.pdf', 'downloadURL' => 'download.php?file=4506T.pdf' ),
				array( 'id' => 'ShortSaleFacilitationAgreement', 'label' => 'Short Sale Facilitation Agreement (SSFA)', 'required' => true , 'fileURL' => 'http://trudocs.com/wp-content/downloads/SSFA.pdf', 'downloadURL' => 'download.php?file=SSFA.pdf' ),
			);
			$lender = array(
				array( 'id' => 'RequestforMortgageAssistance', 'label' => 'Request for Mortgage Assistance (RMA)', 'required' => false , 'downloadURL' => false ),
				array( 'id' => 'UniformBorrowerAssistance', 'label' => 'Uniform Borrower Assistance (UBA)', 'required' => false , 'downloadURL' => false ),
				array( 'id' => 'DODD-Frank', 'label' => 'DODD-Frank', 'required' => false , 'downloadURL' => false ),
				array( 'id' => 'LenderShortSalePackets', 'label' => 'Lender Short Sale Packet', 'required' => false , 'downloadURL' => false ),
				array( 'id' => 'LenderSpecificDocuments', 'label' => 'Lender Specific Document', 'required' => false , 'downloadURL' => false ),
				array( 'id' => 'HomeAffordableForclosureAlternative', 'label' => 'Home Affordable Forclosure Alternative (HAFA)', 'required' => false , 'downloadURL' => false ),
				array( 'id' => 'Co-op', 'label' => 'Co-op (B of A only)', 'required' => false , 'downloadURL' => false ),
				array( 'id' => 'ArmsLengthAfidavid', 'label' => 'Arms Length Afidavid', 'required' => false , 'downloadURL' => false ),
				array( 'id' => 'ApprovalLetter', 'label' => 'Approval Letter', 'required' => false , 'downloadURL' => false ),
			);
			$title = array(
				array( 'id' => 'PreliminaryTitleReport', 'label' => 'Preliminary Title Report', 'required' => false , 'downloadURL' => false ),
				array( 'id' => 'HUD1', 'label' => 'HUD1', 'required' => true , 'downloadURL' => false ),
			);
			if ( $type == 'Listing' ) {
				return $listing;
			} elseif ( $type == 'Purchase Contract' ) {
				return $purchasecontract;
			} elseif ( $type == 'Homeowner' ) {
				return $homeowner;
			} elseif ( $type == 'Lender' ) {
				return $lender;
			} elseif ( $type == 'Title Company' ) {
				return $title;
			} else {
				return array_merge( $listing, $purchasecontract, $homeowner, $lender, $title );
			}
		}



/*|=================|
  |====================================|
  |------------------------------------================================|
  |--------------------------------------------------------------------=================|
  |--| >>>  RATING FUNCTIONS
  |--------------------------------------------------------------------========================================|
  |====================================================================================================================================|
  */



	// DISPLAYS AN SSA's RATING NICE AND PRETTY
   //--------------------------------------------------
		function ssa_rating_show( $userID ) {
			$userAvgRating = get_user_meta( $userID, 'avgRating', true ); // GET SSA AVG RATING
			$userTotalRatings = get_user_meta( $userID, 'numberOfRatings', true ); // GET SSA TOTAL NUMBER OF RATINGS
			for ($i = 1; $i <= 5; $i++) { // LOOP THRU 5 STARS AND CREATE RATING HTML
				if ( $i <= $userAvgRating ) {
					echo '<img src="' . get_bloginfo( 'template_directory' ) . '/images/starGold.png" width="18" height="17"/>';
				} else {
					echo '<img src="' . get_bloginfo( 'template_directory' ) . '/images/starGrey.png" width="18" height="17"/>';
				}
			}
			if ( $userTotalRatings == 1 ) { // SET TEXT STRING
				$RATINGs = 'rating';
			} else {
				$RATINGs = 'ratings';
			}
			echo '<span class="ratingStars_noClick_Text"> ' . $userAvgRating . ' / 5 stars. (' . $userTotalRatings . ' ' . $RATINGs . ')</span>';
		}
	
	// DISPLAYS A LISTING's RATING / NOT CLICKABLE
   //--------------------------------------------------
		function listing_rating_show( $postID ) {
			$listingRating = get_post_meta( $postID, 'listingRating', true ); // LETS GRAB THE CURRENT RATING
			for ($i = 1; $i <= 5; $i++) {
				if ( $i <= $listingRating ) {
					echo '<img src="' . get_bloginfo( 'template_directory' ) . '/images/starGold.png" width="18" height="17"/>';
				} else {
					echo '<img src="' . get_bloginfo( 'template_directory' ) . '/images/starGrey.png" width="18" height="17"/>';
				}
			}
		}
	
	// OUTPUST THE HTML FOR AP's TO RATE A LISTING
   //--------------------------------------------------
		function rate_listing( $postID, $echo = true, $multiQueryParams = false ) {
			$post = get_post( $postID ); // GET THE POST FROM THE ID
			$listingRating = get_post_meta( $postID, 'listingRating', true ); // LETS GRAB THE POSSIBLE CURRENT RATING
			if ( $listingRating != '0' ) { // IF LISTING IS ALREADY RATED
				if ( is_ap() ) {
					if ( $echo ) { echo '<p>Your rating of ' . get_the_author_meta( 'display_name', $post->post_author ) . '\'s performance on this listing:</p>'; }
				} else {
					if ( $echo ) { echo '<p>The Agent / Partner rating of your performance on this listing:</p>'; }
				}
			} elseif ( isset($_GET['rating']) ) { // IF WAS JUST RATED
				set_listing_rating( $postID, $_GET['rating'], $echo );
				$listingRating = get_post_meta( $postID, 'listingRating', true ); // NEED TO GET THE NEW RATING
			} else { // NOT YET RATED, AP CAN RATE THIS LISTING
				if ( is_ap() ) {
					if ( $echo ) { echo '<p>Rate ' . get_the_author_meta( 'display_name', $post->post_author ) . '\'s performance on this listing:</p>'; }
				} else {
					if ( $echo ) { echo '<p>The Agent / Partner has not yet rated your performance on this listing:</p>'; }
				}
			}
			if ( $_GET['filter'] ) { $rateQStr = '&rating='; } else if ( $multiQueryParams ) { $rateQStr = '&rating='; } else{ $rateQStr = '?rating='; }
			for ($i = 1; $i <= 5; $i++) {
				if ( is_ap() && $listingRating == '0' ) { echo '<a href="' . curPageURL() . $rateQStr . $i . '">'; }
				if ( $i <= $listingRating ) {
					echo '<img src="' . get_bloginfo( 'template_directory' ) . '/images/starGold.png" width="18" height="17"/>';
				} else {
					echo '<img src="' . get_bloginfo( 'template_directory' ) . '/images/starGrey.png" width="18" height="17"/>';
				}
				if ( is_ap() && $listingRating == '0' ) { echo '</a> '; }
			}
		}
	
	// SETS A LISTING RATING
   //--------------------------------------------------
		function set_listing_rating( $postID, $rating, $echo ) {
			$post = get_post( $postID ); // GET THE POST FROM THE ID
			$postRating = get_post_meta( $postID, 'listingRating', true ); // GET THE POST RATING
			if ( $postRating == '0' ) { // IF NOT RATED YET, RATE LISTING AND UPDATE SSA RATING
				update_post_meta( $postID, 'listingRating', $rating );
				set_ssa_rating_average( $post->post_author );
				if ( $echo ) { echo '<p>Thank you for rating ' . get_the_author_meta( 'display_name', $post->post_author ) . '</p>'; }
			}
		}
	
	// UPDATES THE SSA's RATING
   //--------------------------------------------------
		function set_ssa_rating_average( $userID ) {
			$query = new WP_Query( 'author=' . $userID . '&meta_key=listingRating' );
			$numberOfRatings = 1;
			$totalStars = 0;
			while ($query->have_posts()) : $query->the_post();
				$listingRating = get_post_meta( $query->post->ID, 'listingRating', true );
				if ( $listingRating != '0' ) {
					$totalStars = $totalStars + intval( $listingRating );
					$numberOfRatings++;
				}
			endwhile;
			$avgRating = $totalStars / $numberOfRatings;
			update_user_meta( $userID, 'avgRating', $avgRating );
			update_user_meta( $userID, 'numberOfRatings', $numberOfRatings );
			set_ssa_rating_wieght( $userID );
			//return $totalStars . ' / ' . $numberOfRatings . ' = ' .$avgRating . ' WEIGHT: ' . set_ssa_rating_wieght( $userID ); // FOR DEV
		}
	
	// CALCs AND SETS A SSA's WIEGHTED RATING
   //--------------------------------------------------
		function set_ssa_rating_wieght( $userID ) {
			$SSAs = get_users( array( 'role' => 'assistant', 'meta_key' => 'avgRating' ) );
			$ssaCount = 0;
			$V = 0;
			$totalOfAllRatings = 0;
			foreach ( $SSAs as $ssa ) {
				$ssaCount++;
				$V = $V + get_user_meta( $ssa->ID, 'numberOfRatings', true );
				$totalOfSSaAvgRatings = $totalOfSSaAvgRatings + get_user_meta( $ssa->ID, 'numberOfRatings', true );
			}
			$AV = $V / $ssaCount;
			$v = get_user_meta( $userID, 'numberOfRatings', true );
			$R = $totalOfSSaAvgRatings / $ssaCount;
			$r = get_user_meta( $userID, 'avgRating', true );
			$ratingWieght = (($AV * $R) + ($v * $r)) / ($AV + $v);
			update_user_meta( $userID, 'ratingWieght', $avgRating );
			//return '((' . $AV . ' * ' . $R . ') + (' . $v . ' * ' . $r . ')) / (' . $AV . ' + ' . $v . ') = ' . $ratingWieght; // FOR DEV
		}



	
/*|=================|
  |====================================|
  |------------------------------------================================|
  |--------------------------------------------------------------------=================|
  |--| >>> DOCUMENT TRACKING / AUTO EMAILER
  |--------------------------------------------------------------------========================================|
  |====================================================================================================================================|
  */



	// CUSTOM CRON TIME
   //--------------------------------------------------
		function cron_add_every_three_days( $schedules ) {
			// Adds once weekly to the existing schedules.
			$interval = (60*30);//*60*24*3;
			$schedules['every_three_days'] = array(
				'interval' => $interval,
				'display' => __( 'Once every 3 days' )
			);
			return $schedules;
		}
		add_filter( 'cron_schedules', 'cron_add_every_three_days' );
	
	
	// ADD EMAIL FUNCTION TO CRON SCHED
   //--------------------------------------------------
		function queue_reqDocsMissingEmail() {
			if ( !wp_next_scheduled( 'reqDocsMissingEmail_Cron' ) ) {
				wp_schedule_event( time(), 'every_three_days', 'reqDocsMissingEmail_Cron');
			}
		}
		add_action('wp', 'queue_reqDocsMissingEmail');
		
	// REQUIRED DOC MISSING EMAILING FUNCTION
   //--------------------------------------------------
		function send_reqDocsMissingEmail() {
			
			// Query Inactive listings missing req docs
				$args = array(
					'include' => 670,
					'post_type' => 'post',
					/*'posts_per_page' => -1,
					'meta_query' => array(
						array(
							'key' => 'listingStatus',
							'value' => 'Closed',
							'compare' => 'NOT LIKE'
						),
						array(
							'key' => 'documentTracking',
							'value' => 'autoTracking'
						),
						array(
							'key' => 'reqDocsMissing',
							'value' => true
						),
						array(
							'key' => 'listingUpdated',
							'value' => time() - (7 * 24 * 60 * 60),
							'type' => 'numeric',
							'compare' => '<='
						)
					)*/
				);
				$the_query = new WP_Query( $args );
				
			// Get the listings and needed info
				while ( $the_listing->have_posts() ) : $the_listing->the_post();
					
					// GET INFO NEEDED
						$apID = $the_listing->post_author;
						$ap = get_user_by('id', $apID);
						$listingAddress = get_the_title();
						$listingLink = get_permalink();

					// EMAIL TO SSA
						$message = 'Hey ' . $ap->first_name . ',<br />We noticed your missing documents on your listing for ' . $listingAddress . '.,br />If you have some documents you can upload, or if the listing can be updated, you can do so now by <a href="' . $listingLink . '">clicking here</a>. Thanks!';
						add_filter('wp_mail_content_type',create_function('', 'return "text/html";'));
						//$headers[] = 'From: [CRON] <CRON@trudocs.com>';
						wp_mail('jlareaux@gmail.com', 'CRON RUN', $message, $headers);
						
				endwhile;
		}
		add_action('reqDocsMissingEmail_Cron', 'send_reqDocsMissingEmail');
		
		
		
		
		
		
		

?>